package com.jhws.business.local.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.face.bo.FaceInfo;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.db.BaseDao;
import com.jhws.util.GsonUtil;
import com.jhws.util.LogHelper;
import com.jhws.util.net.JhHttpClient;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
public class FaceSynchService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private OSSClientService ossClientService;
    @Resource
    private LocalService localService;

    public void saveFace(FaceInfo faceInfo) {
        faceInfo.setIsSynch(LocalConstant.SYNCH_STATE_YES);
        BaseDao.saveOrUpdate(faceInfo);
    }

    public void deleteFace(FaceInfo faceInfo) throws Exception {
        BaseDao.delete(faceInfo);
    }

    public List<FaceInfo> findFaceWhere(String whereStr) throws Exception {
        return BaseDao.findList("from FaceInfo " + whereStr);
    }

    public void mergeFace(String serverUrl, String commCode, Map<String, String> headers) throws Exception {
        List<FaceInfo> list = findFaceWhere("where is_synch != '" + LocalConstant.SYNCH_STATE_YES + "' and comm_code='" + commCode + "'");
        if (list == null || list.isEmpty()) {
            return;
        }
        JhHttpClient hp = new JhHttpClient();
        for (FaceInfo faceInfo : list) {
            try {
                FaceInfo info = new FaceInfo();
                BeanUtils.copyProperties(info, faceInfo);// 属性拷贝
                File file = localService.getFile("file/face/2405521491656704.data");
                String destKey = "comm/0008/face/" + file.getName();
                ossClientService.updateFile(destKey, file);
                info.setFaceFeature(destKey);
                file = localService.getFile("file/face/2405521491656704.jpg");
                destKey = "comm/0008/face/" + file.getName();
                ossClientService.updateFile(destKey, file);
                info.setImageUrl(destKey);
                String s = hp.postJson(serverUrl + "api/localSynch/face/faces", GsonUtil.toJson(info), headers);
                LogHelper.e("----------------------->    "+s);
                JsonRespData respData = JSON.parseObject(s, JsonRespData.class);
                if (respData.ret_code > 0) {
                    if (faceInfo.getIsSynch() == LocalConstant.SYNCH_STATE_NO) {
                        saveFace(faceInfo);
                    } else if (faceInfo.getIsSynch() == LocalConstant.SYNCH_STATE_DEL) {
                        deleteFace(faceInfo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
